package com.example.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.example.common.core.enums.ResultCode;
import com.example.common.security.exception.ServiceException;
import com.example.system.domain.video.Video;
import com.example.system.domain.video.dto.VideoQueryDTO;
import com.example.system.domain.video.vo.VideoVO;
import com.example.system.mapper.video.VideoMapper;
import com.example.system.service.IVideoService;
import com.github.pagehelper.PageHelper;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Service
@Transactional(readOnly = true)
public class VideoServiceImpl implements IVideoService {

    @Autowired
    private VideoMapper videoMapper;

    private static final String COURSE_DIR = Paths.get(System.getProperty("user.dir")).toString();

    @Override
    public List<VideoVO> list(VideoQueryDTO videoQueryDTO) {
        PageHelper.startPage(videoQueryDTO.getPageNum(), videoQueryDTO.getPageSize());
        return videoMapper.selectListByCourseId(videoQueryDTO.getCourseId());
    }

    @Override
    public VideoVO get(Long videoId) {
        Video video = videoMapper.selectById(videoId);
        if (video == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        VideoVO videoVO = new VideoVO();
        BeanUtil.copyProperties(video, videoVO);
        return videoVO;
    }

    @Override
    public void streamVideo(Long videoId, HttpServletResponse response) {
        // 根据视频 ID 获取视频文件路径
        Video video = videoMapper.selectById(videoId);
        if (video == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        File videoFile = Paths.get(COURSE_DIR, video.getPath(), video.getVideoName()).toFile();

        response.setContentType("video/mp4");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + URLEncoder.encode(videoFile.getName()) + "\"");

        // 设置响应流
        try (InputStream videoStream = new FileInputStream(videoFile); OutputStream outStream = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = videoStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
} 